package cn.lk.netty.rpc.registry;

import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @ClassName ServiceRegister
 * @Deseription TODO
 * @Author hu'nan
 * @Date 2020/4/5 10:06
 * @Version 1.0
 **/
@Component
public class ServiceRegistry {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private static final String ZK_REGISTER_PATH = "/rpc";

    @Value("${registry.address}")
    private String registryAddress;

    /**
     * 连接 zookeeper
     * @return
     */
    private ZkClient connectServer(){
        return new ZkClient(registryAddress, 20000, 20000);
    }

    /**
     * 创建主节点
     * @param client
     */
    private void addRootNode(ZkClient client){
        boolean exists = client.exists(ZK_REGISTER_PATH);
        if (!exists){
            client.createPersistent(ZK_REGISTER_PATH);
            logger.info("创建 zookeeper 主节点 {} 成功", ZK_REGISTER_PATH);
        }
    }

    /**
     * 创建子节点
     * @param client
     * @param data
     */
    private void createNode(ZkClient client, String data){
        // 子节点必须是临时节点。这样，生产者端停掉之后，才能通知到消费者，把此服务从服务列表中剔除。
        String path = client.create(ZK_REGISTER_PATH + "/provider", data, CreateMode.EPHEMERAL_SEQUENTIAL);
        logger.info("创建 zookeeper 数据节点({} => {}) 成功", path, data);
    }

    public void register(String data){
        if (data != null){
            ZkClient client = connectServer();
            if (client != null){
                addRootNode(client);
                createNode(client, data);
            }
        }
    }
}
